package com.tledu.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tledu.commont.ResultVo;
import com.tledu.pojo.User;
import com.tledu.service.UserService;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;

/**
 * @Author 王付岩
 * @InterfaceName UserController
 * @Date 2022/5/24 15:57
 * 用户
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public ResultVo login( User user){
        User res = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUser_name, user.getUser_name()).eq(User::getUser_password, user.getUser_password()));
        if (res == null){
            return new ResultVo(400, "没有此用户", null);
        }
        JwtBuilder builder = Jwts.builder();
        String token = builder.setSubject(String.valueOf(res.getUser_id())) //设置token中携带的数据
                .setIssuedAt(new Date())   //设置token生成时间
                .setId(String.valueOf(res.getUser_id()))   //设置token的Id
                .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000))  //设置过期时间
                .signWith(SignatureAlgorithm.HS256, "NoError") //设置加密方式和密码
                .compact();
        HashMap<Object,Object> hashMap =new HashMap();
        hashMap.put("token",token);
        hashMap.put("user",res);
        return new ResultVo(200,"登录成功",hashMap);

    }


}
